import os

from pydub import AudioSegment, silence

from utils.file_io import listdir

if __name__ == '__main__':
    wan_root_path = "wav"
    wav_list = []
    min_silence_len = 50  # 当语音间隔长度大于这个值时会进行一次切除，单位：ms
    listdir(wan_root_path + "/output", wav_list)
    if not os.path.exists(wan_root_path + "/cut_silent_output/"):
        os.mkdir(wan_root_path + "/cut_silent_output/")
    print(f"读取到的文件列表：{wav_list}")
    for file_path in wav_list:
        if not file_path.endswith(".wav"):
            continue
        file_name = file_path.split("/")[-1]
        sound = AudioSegment.from_wav(file_path)
        sound_cut_list = silence.split_on_silence(sound, min_silence_len=min_silence_len, silence_thresh=-30,
                                                  keep_silence=25)
        cut_file = AudioSegment.silent(1)
        for sound_cut in sound_cut_list:
            cut_file = cut_file + AudioSegment.silent(min_silence_len) + sound_cut
        cut_file.export(wan_root_path + "/cut_silent_output/" + file_name, format="wav")

